package com.member.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.member.common.core.domain.model.LoginUser;
import com.member.common.enums.*;
import com.member.common.exception.ServiceException;
import com.member.common.utils.DateUtils;
import com.member.common.utils.StringUtils;
import com.member.common.utils.bean.BeanUtils;
import com.member.shop.domain.*;
import com.member.shop.dto.EvaluateTemplateDto;
import com.member.shop.dto.InsertEvaluateDto;
import com.member.shop.mapper.SysBizGoodsEvaluateMapper;
import com.member.shop.mapper.SysBizImportFailMapper;
import com.member.shop.mapper.SysBizOrderMapper;
import com.member.shop.mapper.SysBizUserMapper;
import com.member.shop.service.*;
import com.member.shop.vo.GoodsEvaluateVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

import static com.member.common.utils.SecurityUtils.getLoginUser;

/**
 * 商品评价Service业务层处理
 *
 * @author wangxin
 * @date 2024-01-08
 */
@Service
public class SysBizGoodsEvaluateServiceImpl extends ServiceImpl<SysBizGoodsEvaluateMapper, SysBizGoodsEvaluate> implements ISysBizGoodsEvaluateService {
    @Resource
    private SysBizGoodsEvaluateMapper sysBizGoodsEvaluateMapper;
    @Resource
    private ISysBizUserService sysBizUserService;

    @Resource
    private SysBizUserMapper sysBizUserMapper;

    @Resource
    private ISysBizOrderService sysBizOrderService;
    @Resource
    private ISysBizOrderGoodsService sysBizOrderGoodsService;
    @Resource
    private SysBizOrderMapper sysBizOrderMapper;
    @Resource
    private ISysBizGoodsSkuService sysBizGoodsSkuService;


    /**
     * 查询商品评价
     *
     * @param id 商品评价主键
     * @return 商品评价
     */
    @Override
    public SysBizGoodsEvaluate selectSysBizGoodsEvaluateById(Long id) {
        return sysBizGoodsEvaluateMapper.selectById(id);
    }

    /**
     * 查询商品评价列表
     *
     * @param sysBizGoodsEvaluate 商品评价
     * @return 商品评价
     */
    @Override
    public List<SysBizGoodsEvaluate> selectSysBizGoodsEvaluateList(LambdaQueryWrapper<SysBizGoodsEvaluate> queryWrapper) {
        return sysBizGoodsEvaluateMapper.selectList(queryWrapper);
    }


    /**
     * 查询商品评价列表(后端)
     *
     * @param sysBizGoodsEvaluate 商品评价
     * @return 商品评价
     */
    @Override
    public List<SysBizGoodsEvaluate> selectSysBizGoodsEvaluateList(SysBizGoodsEvaluate sysBizGoodsEvaluate) {
        return sysBizGoodsEvaluateMapper.selectSysBizGoodsEvaluateList1(sysBizGoodsEvaluate);

    }

    /**
     * 新增商品评价
     *
     * @param sysBizGoodsEvaluate 商品评价
     * @return 结果
     */
    @Override
    public int insertSysBizGoodsEvaluate(SysBizGoodsEvaluate sysBizGoodsEvaluate) {
        sysBizGoodsEvaluate.setCreateTime(DateUtils.getNowDate());
        return sysBizGoodsEvaluateMapper.insert(sysBizGoodsEvaluate);
    }

    /**
     * 修改商品评价
     *
     * @param sysBizGoodsEvaluate 商品评价
     * @return 结果
     */
    @Override
    public int updateSysBizGoodsEvaluate(SysBizGoodsEvaluate sysBizGoodsEvaluate) {
        sysBizGoodsEvaluate.setUpdateTime(DateUtils.getNowDate());

        if (StringUtils.isNotEmpty(sysBizGoodsEvaluate.getMerchantResponse())) {
            sysBizGoodsEvaluate.setStatus(ResponseStatuslEnum.REPLIED.getKey());
            sysBizGoodsEvaluate.setResponseTime(DateUtils.getNowDate());
        }
        if (StringUtils.isNotEmpty(sysBizGoodsEvaluate.getMerchantResponse()) && StringUtils.isNotEmpty(sysBizGoodsEvaluate.getResponseAdd())) {
            sysBizGoodsEvaluate.setStatus(ResponseStatuslEnum.FOLLOW_UP_REPLIED.getKey());
            sysBizGoodsEvaluate.setResponseAddTime(DateUtils.getNowDate());

        }
        return sysBizGoodsEvaluateMapper.updateById(sysBizGoodsEvaluate);
    }

    /**
     * 批量删除商品评价
     *
     * @param ids 需要删除的商品评价主键
     * @return 结果
     */
    @Override
    public int deleteSysBizGoodsEvaluateByIds(Long[] ids) {
        return sysBizGoodsEvaluateMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除商品评价信息
     *
     * @param id 商品评价主键
     * @return 结果
     */
    @Override
    public int deleteSysBizGoodsEvaluateById(Long id) {
        SysBizGoodsEvaluate sysBizGoodsEvaluate = new SysBizGoodsEvaluate();
        sysBizGoodsEvaluate.setId(id);
        sysBizGoodsEvaluate.setUpdateTime(DateUtils.getNowDate());
        sysBizGoodsEvaluate.setDeleted(OrderDeleteEnum.DELETE.getKey());
        return sysBizGoodsEvaluateMapper.updateById(sysBizGoodsEvaluate);
    }

    @Override
    public List<GoodsEvaluateVo> queryGoodsEvaluateByGoodsId(Long id) {
        List<GoodsEvaluateVo> goodsEvaluateVoList = new ArrayList<>();
        LambdaQueryWrapper<SysBizGoodsEvaluate> sysBizGoodsEvaluateLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysBizGoodsEvaluateLambdaQueryWrapper.eq(SysBizGoodsEvaluate::getGoodsId, id);
        sysBizGoodsEvaluateLambdaQueryWrapper.eq(SysBizGoodsEvaluate::getDisplayed, EnableStatusEnum.ENABLE.getKey());
        sysBizGoodsEvaluateLambdaQueryWrapper.eq(SysBizGoodsEvaluate::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
        sysBizGoodsEvaluateLambdaQueryWrapper.orderByDesc(SysBizGoodsEvaluate::getId);
        List<SysBizGoodsEvaluate> sysBizGoodsEvaluates = sysBizGoodsEvaluateMapper.selectList(sysBizGoodsEvaluateLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(sysBizGoodsEvaluates)) {
            for (SysBizGoodsEvaluate sysBizGoodsEvaluate : sysBizGoodsEvaluates) {
                GoodsEvaluateVo goodsEvaluateVo = new GoodsEvaluateVo();
                BeanUtils.copyProperties(sysBizGoodsEvaluate, goodsEvaluateVo);
                goodsEvaluateVoList.add(goodsEvaluateVo);
            }
        }
        return goodsEvaluateVoList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertEvaluate(Long userId, List<InsertEvaluateDto> insertEvaluateDtos) {
        // 判断是否追评
        Date nowDate = DateUtils.getNowDate();
        Long orderId = null;
        for (InsertEvaluateDto insertEvaluateDto : insertEvaluateDtos) {
            orderId = insertEvaluateDto.getOrderId();
            if (insertEvaluateDto.getType() == 1) {
                LambdaQueryWrapper<SysBizGoodsEvaluate> sysBizGoodsEvaluateLambdaQueryWrapper = new LambdaQueryWrapper<>();
                sysBizGoodsEvaluateLambdaQueryWrapper.eq(SysBizGoodsEvaluate::getOrderId, insertEvaluateDto.getOrderId());
                sysBizGoodsEvaluateLambdaQueryWrapper.eq(SysBizGoodsEvaluate::getUserId, userId);
                SysBizGoodsEvaluate sysBizGoodsEvaluate = sysBizGoodsEvaluateMapper.selectOne(sysBizGoodsEvaluateLambdaQueryWrapper);
                if (sysBizGoodsEvaluate == null) {
                    throw new ServiceException("追评未找到评论");
                }
                sysBizGoodsEvaluate.setContentAdd(insertEvaluateDto.getContentText());
                sysBizGoodsEvaluate.setImageAdd(insertEvaluateDto.getContentImage());
                sysBizGoodsEvaluate.setUserAddTime(nowDate);
                sysBizGoodsEvaluate.setStatus(2);
                sysBizGoodsEvaluateMapper.updateById(sysBizGoodsEvaluate);
                continue;
            }

            SysBizUser sysBizUser = sysBizUserService.selectSysBizUserById(userId);
            SysBizGoodsEvaluate sysBizGoodsEvaluate = new SysBizGoodsEvaluate();
            sysBizGoodsEvaluate.setAvatar(sysBizUser.getAvatar());
            sysBizGoodsEvaluate.setUserId(userId);
            sysBizGoodsEvaluate.setScore(insertEvaluateDto.getScore());
            sysBizGoodsEvaluate.setGoodsId(insertEvaluateDto.getGoodsId());
            sysBizGoodsEvaluate.setDeleted(OrderDeleteEnum.NOT_DELETE.getKey());
            sysBizGoodsEvaluate.setIsAnonymous(insertEvaluateDto.getIsAnonymous());
            sysBizGoodsEvaluate.setDisplayed(EnableStatusEnum.NO_ENABLE.getKey());
            sysBizGoodsEvaluate.setContentImage(insertEvaluateDto.getContentImage());
            sysBizGoodsEvaluate.setNickName(sysBizUser.getNickName());
            sysBizGoodsEvaluate.setSpecsKey(insertEvaluateDto.getSpecsKey());
            sysBizGoodsEvaluate.setContentText(insertEvaluateDto.getContentText());
            sysBizGoodsEvaluate.setOrderId(insertEvaluateDto.getOrderId());
            sysBizGoodsEvaluate.setPhone(sysBizUser.getUserPhone());
            sysBizGoodsEvaluate.setCreateTime(nowDate);
            sysBizGoodsEvaluate.setCreateBy(sysBizUser.getNickName());
            sysBizGoodsEvaluateMapper.insert(sysBizGoodsEvaluate);
        }
        // 将订单状态修改为交易完成
        sysBizOrderService.update(new LambdaUpdateWrapper<SysBizOrder>().set(SysBizOrder::getStatus, 50).eq(SysBizOrder::getId, orderId));
    }

    @Resource
    private SysBizImportFailMapper sysBizImportFailMapper;
    @Resource
    private ISysBizCommentPicService sysBizCommentPicService;
    /**
     * 商品评价导入
     */
    ;

    @Override
    public int importData(List<EvaluateTemplateDto> evaluateTemplateDtos, boolean updateSupport, String operName) {
        int failureNum = 0;
        if (StringUtils.isNull(evaluateTemplateDtos) || evaluateTemplateDtos.isEmpty() || evaluateTemplateDtos.stream().allMatch(Objects::isNull)) {
            failureNum = -1;
            return failureNum;
        }


        for (EvaluateTemplateDto evaluateTemplateDto : evaluateTemplateDtos) {
            SysBizImportFail sysBizImportFail = new SysBizImportFail();
            LoginUser loginUser = getLoginUser();


            sysBizImportFail.setUserId(loginUser.getUserId());
            sysBizImportFail.setType(ImportFailEnum.EVALUATION_IMPORT.getKey());
            sysBizImportFail.setNickName(evaluateTemplateDto.getNickName());
            //sysBizImportFail.setUserPhone(evaluateTemplateDto.getPhone());
            sysBizImportFail.setGoodsCode(evaluateTemplateDto.getGoodsCode());
            sysBizImportFail.setScore(evaluateTemplateDto.getScore());
            sysBizImportFail.setSpecsKey(evaluateTemplateDto.getSpecsKey());
            sysBizImportFail.setContentText(evaluateTemplateDto.getContentText());

            if (evaluateTemplateDto.getNickName().isEmpty() || evaluateTemplateDto.getNickName().length() > 10) {
                sysBizImportFail.setFailureReason("评价用户名称不能为空或者长度不能超过11位");
                sysBizImportFailMapper.insert(sysBizImportFail);
                failureNum++;
                continue;
            }
//            if (evaluateTemplateDto.getPhone().isEmpty() || evaluateTemplateDto.getPhone().length() > 11) {
//                sysBizImportFail.setFailureReason("手机号不能为空或者长度不能超过11位");
//                sysBizImportFailMapper.insert(sysBizImportFail);
//                failureNum++;
//                continue;
//            }
            if (evaluateTemplateDto.getGoodsCode().isEmpty() || evaluateTemplateDto.getGoodsCode().length() > 15) {
                sysBizImportFail.setFailureReason("商品编码不能为空或者长度不能超过15位");
                sysBizImportFailMapper.insert(sysBizImportFail);
                failureNum++;
                continue;
            }
//            if (evaluateTemplateDto.getOrderCode().isEmpty() || evaluateTemplateDto.getOrderCode().length() > 15) {
//                sysBizImportFail.setFailureReason("订单编码不能为空或者长度不能超过14位");
//                sysBizImportFailMapper.insert(sysBizImportFail);
//                failureNum++;
//                continue;
//            }
            if (!evaluateTemplateDto.getScore().isEmpty()) {
                try {
                    Long number = Long.parseLong(evaluateTemplateDto.getScore());
                    if (number < 1 || number > 5) {
                        sysBizImportFail.setFailureReason("星数必须为数字1-5之间");
                        sysBizImportFailMapper.insert(sysBizImportFail);
                        failureNum++;
                        continue;
                    }
                } catch (NumberFormatException e) {
                    sysBizImportFail.setFailureReason("星数必须为数字1-5之间");
                    sysBizImportFailMapper.insert(sysBizImportFail);
                    failureNum++;
                    continue;
                }
            } else {
                sysBizImportFail.setFailureReason("星数不能为空");
                sysBizImportFailMapper.insert(sysBizImportFail);
                failureNum++;
                continue;
            }
            if (evaluateTemplateDto.getContentText().isEmpty() || evaluateTemplateDto.getContentText().trim().length() > 300) {
                sysBizImportFail.setFailureReason("评价内容不能为空或者长度不能超过300位");
                sysBizImportFailMapper.insert(sysBizImportFail);
                failureNum++;
                continue;
            }
            if (evaluateTemplateDto.getSpecsKey().isEmpty() || evaluateTemplateDto.getSpecsKey().length() > 30) {
                sysBizImportFail.setFailureReason("评价规格不能为空或者长度不能超过30位");
                sysBizImportFailMapper.insert(sysBizImportFail);
                failureNum++;
                continue;
            }

            // 验证手机号是否存在
//            if (sysBizUserService.hasUserPhone(evaluateTemplateDto.getPhone())) {
//                通过手机号查询用户昵称
//                LambdaQueryWrapper<SysBizUser> sysBizUserLambdaQueryWrapper = new LambdaQueryWrapper<SysBizUser>();
//                sysBizUserLambdaQueryWrapper.eq(SysBizUser::getUserPhone, evaluateTemplateDto.getPhone());
//                SysBizUser sysBizUser1 = sysBizUserMapper.selectOne(sysBizUserLambdaQueryWrapper);


            //验证订单号是否存在
//                SysBizOrder sysBizOrder = sysBizGoodsEvaluateMapper.hasOrderCode(evaluateTemplateDto.getOrderCode());
//                if (sysBizOrder == null) {
//                    sysBizImportFail.setFailureReason("验证订单号不存在或者订单还未结束");
//                    sysBizImportFailMapper.insert(sysBizImportFail);
//                    failureNum++;
//                    continue;
//                }


            //验证商品号是否存在
            SysBizGoods sysBizGoods = sysBizGoodsEvaluateMapper.hasGoodsCode(evaluateTemplateDto.getGoodsCode());
            if (sysBizGoods == null) {
                sysBizImportFail.setFailureReason("商品编号不存在");
                sysBizImportFailMapper.insert(sysBizImportFail);
                failureNum++;
                continue;
            }
            //验证商品规格是否存在
            SysBizGoodsSku sysBizGoodsSku = sysBizGoodsSkuService.selectSysBizGoodsSkuByGoodsIdAndKey(sysBizGoods.getId(), evaluateTemplateDto.getSpecsKey());
            if (sysBizGoodsSku == null) {
                sysBizImportFail.setFailureReason("商品规格不存在");
                sysBizImportFailMapper.insert(sysBizImportFail);
                failureNum++;
                continue;
            }

            //验证是否评价过了
//                SysBizGoodsEvaluate sysBizGoodsEvaluate = sysBizGoodsEvaluateMapper.hasEvaluate(evaluateTemplateDto);
//                if (sysBizGoodsEvaluate != null) {
//                    sysBizImportFail.setFailureReason("该用户已经评价过");
//                    sysBizImportFailMapper.insert(sysBizImportFail);
//                    failureNum++;
//                    continue;
//                } else {
            SysBizGoodsEvaluate sysBizGoodsEvaluate1 = new SysBizGoodsEvaluate();
            //评价头像
            LambdaQueryWrapper<SysBizCommentPic> queryWrapper = new LambdaQueryWrapper<SysBizCommentPic>();
            queryWrapper.eq(SysBizCommentPic::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
            List<SysBizCommentPic> list = sysBizCommentPicService.selectSysBizCommentPicList(queryWrapper);
            if (list != null || list.size() > 0) {
                Random random = new Random();
                int index = random.nextInt(list.size());
                sysBizGoodsEvaluate1.setAvatar(list.get(index).getCommentPic());
            }
            sysBizGoodsEvaluate1.setSource(SourceEnum.SHIPPED.getKey());
            sysBizGoodsEvaluate1.setNickName(evaluateTemplateDto.getNickName());
//                    sysBizGoodsEvaluate1.setPhone(evaluateTemplateDto.getPhone());
//                    sysBizGoodsEvaluate1.setOrderId(sysBizOrder.getId());
            sysBizGoodsEvaluate1.setGoodsId(sysBizGoods.getId());
            sysBizGoodsEvaluate1.setScore(Integer.parseInt(evaluateTemplateDto.getScore()));
            sysBizGoodsEvaluate1.setContentText(evaluateTemplateDto.getContentText());
            sysBizGoodsEvaluate1.setDisplayed(EnableStatusEnum.ENABLE.getKey());
            sysBizGoodsEvaluate1.setSpecsKey(evaluateTemplateDto.getSpecsKey());
            sysBizGoodsEvaluateMapper.insert(sysBizGoodsEvaluate1);

            //更新订单表的待评价
//                    LambdaQueryWrapper<SysBizOrder> sysBizOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                    sysBizOrderLambdaQueryWrapper.eq(SysBizOrder::getId,sysBizOrder.getId());
//                    SysBizOrder sysBizOrder1 = new SysBizOrder();
//                    sysBizOrder1.setId(sysBizOrder.getId());
//                    sysBizOrder1.setStatus(OrderSatusEnum.TRANSACTION_COMPLETED.getKey());
//                    sysBizOrderMapper.updateById(sysBizOrder1);
            continue;
//                }
//            } else {
//                sysBizImportFail.setFailureReason("手机号不存在");
//                sysBizImportFailMapper.insert(sysBizImportFail);
//                failureNum++;
//                continue;
//            }

        }
        return failureNum;
    }

    /**
     * 导出商品评价列表
     */
    @Override
    public List<SysBizGoodsEvaluateOut> selectSysBizGoodsEvaluateListOut(SysBizGoodsEvaluate sysBizGoodsEvaluate) {
        return sysBizGoodsEvaluateMapper.selectSysBizGoodsEvaluateListOut(sysBizGoodsEvaluate);
    }

    public static <T> T pickOne(List<T> list) {
        Random random = new Random();
        int index = random.nextInt(list.size());
        return list.get(index);
    }
}
